package com.example.yichuangyun.mvvm.ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.bumptech.glide.Glide;
import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityAddContactsBinding;
import com.example.yichuangyun.dialog.EditDialog;
import com.example.yichuangyun.dialog.SinglePickerView;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.FileModel;
import com.example.yichuangyun.model.business.CompanyModel;
import com.example.yichuangyun.model.business.LabelModel;
import com.example.yichuangyun.model.contacts.ContactWayModel;
import com.example.yichuangyun.model.contacts.ContactsTagModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.ui.activity.view.AddContactsViewModel;
import com.example.yichuangyun.mvvm.ui.adapter.CompanyAdapter;
import com.example.yichuangyun.mvvm.ui.adapter.ContactsPhoneAdapter;
import com.example.yichuangyun.ui.activity.business.ProductActivity;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.UMengUtil;
import com.example.yichuangyun.utils.pictrue.GlideEngine;
import com.example.yichuangyun.utils.producttreelist.ProductNodeModel;
import com.example.yichuangyun.widget.TagContainerLayout;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureSelectorStyle;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;

/**
 * 添加联系人
 */
public class AddContactsActivity extends BaseActivity<ActivityAddContactsBinding, AddContactsViewModel> implements ContactsPhoneAdapter.OnPhoneButtonChangeListener, CompanyAdapter.OnCompanyButtonChangeListener {

    private File file;
    private ActivityResultLauncher<Intent> launcherResult;
    private ActivityResultLauncher<Intent> requestAddSource;
    private List<ContactWayModel> numData = new ArrayList<>();
    private List<CompanyModel> companyData = new ArrayList<>();
    private final List<String> historyTags = new ArrayList<>();
    private List<ContactsTagModel> historyTagsData = new ArrayList<>();
    private final List<ContactsTagModel> historyTagsData2 = new ArrayList<>();
    private List<String> mTags = new ArrayList<>();
    private boolean isEditTag;
    private EditDialog addTagDialog;
    private final List<FileModel> imgList = new ArrayList<>();
    private final List<String> sexData = new ArrayList<>();
    private Integer sex;
    private int mPosition;
    /**
     * 联系人来源
     */
    private HashSet<ProductNodeModel> sourceData = new HashSet<>();
    /**
     * 联系人来源id
     */
    private String contactSourceType = "1";
    /**
     * 联系人来源名称
     */
    private String contactSource;

    private String contactId;
    private int contactType;
    private ContactsPhoneAdapter contactsPhoneAdapter;
    private CompanyAdapter companyAdapter;

    private final List<String> followStatus = new ArrayList<>();
    private final List<LabelModel> followStatusData = new ArrayList<>();
    private Integer followStatusCode;
    private int flag;

    @Override
    protected AddContactsViewModel bindModel() {
        return getViewModel(this, AddContactsViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        launcherResult = createActivityResultLauncher();
        initDialog();
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            flag = bundle.getInt(Constant.flagKey, 0);
            switch (flag) {
                case 0:
                    initTitleBar(getString(R.string.add_contacts));
                    numData.add(new ContactWayModel(1, 1));
                    companyData.add(new CompanyModel());
                    break;
                case 1:
                    initTitleBar(getString(R.string.edit_contacts));
                    binding.rlContactsFrom.setEnabled(false);
                    binding.ivFrom.setVisibility(View.INVISIBLE);
                    contactId = bundle.getString(Constant.idKey);
                    contactType = bundle.getInt(Constant.contactTypeKey);
                    if (contactType == 2 || contactType == 3) {
                        binding.tvAddTag.setVisibility(View.GONE);
                        binding.tvEditTag.setVisibility(View.GONE);
                        binding.tagLayoutHistory.setVisibility(View.GONE);
                    }
                    binding.rlFollowStatus.setVisibility(View.VISIBLE);
                    followStatusData.add(new LabelModel(getString(R.string.not_follow), 10, false));
                    followStatusData.add(new LabelModel(getString(R.string.following), 20));
                    followStatusData.add(new LabelModel(getString(R.string.no_intention), 40));
                    followStatusData.add(new LabelModel(getString(R.string.already_transform), 30));
                    for (LabelModel labelModel : followStatusData) {
                        followStatus.add(labelModel.getRemark());
                    }
                    break;
                case 2: // 企业过来
                    initTitleBar(getString(R.string.add_contacts));
                    String comName = bundle.getString(Constant.nameKey);
                    String creditNo = bundle.getString(Constant.creditNoKey);
                    numData.add(new ContactWayModel(1, 1));
                    companyData.add(new CompanyModel(comName, 1, creditNo));
                    break;
                case 3: // 企业联系电话过来
                    initTitleBar(getString(R.string.add_contacts));
                    String comName2 = bundle.getString(Constant.nameKey);
                    String creditNo2 = bundle.getString(Constant.creditNoKey);
                    String phone = bundle.getString(Constant.phoneKey);
                    contactSourceType = String.valueOf(bundle.getInt(Constant.contactSourceTypeKey));
                    contactSource = contactSourceType.equals("8") ? getString(R.string.qynb) : getString(R.string.work_address_book);
                    viewModel.contactFrom.setValue(contactSource);
                    numData.add(new ContactWayModel(1, phone, 1));
                    companyData.add(new CompanyModel(comName2, 1, creditNo2));
                    break;
            }
        }
        binding.setAddContactsViewModel(viewModel);
        viewModel.weight.setValue("1");

        requestAddSource = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK) {
                if (result.getData() != null) {
                    sourceData = (HashSet<ProductNodeModel>) result.getData().getSerializableExtra(Constant.listKey);
                    if (sourceData != null) {
                        contactSource = sourceData.iterator().next().getTitle();
                        contactSourceType = sourceData.iterator().next().getId();
                        viewModel.contactFrom.setValue(contactSource);
                    }
                    changeBtnStatus();
                }
            }
        });

        sexData.add(context.getString(R.string.sex_boy));
        sexData.add(context.getString(R.string.sex_girl));
        sexData.add(context.getString(R.string.unknown));

        contactsPhoneAdapter = new ContactsPhoneAdapter(context, numData, this);
        binding.recyclerViewNum.setAdapter(contactsPhoneAdapter);

        companyAdapter = new CompanyAdapter(context, companyData, this, flag);
        binding.recyclerViewCompany.setAdapter(companyAdapter);

        // ---------------联系人标签-------------------
        binding.tagLayout.setTags(mTags);
        binding.tagLayout.setEnableCross(contactType == 1);
        viewModel.getTag();
    }

    private void initSinglePickerView(int flag, List<String> data, String title) {
        SinglePickerView singlePickerView = new SinglePickerView((Activity) context, title, data) {
            @Override
            public void confirm(String label, int position) {
                if (flag == 1) {
                    // 性别：1男，2女，3未知
                    sex = label.equals(context.getString(R.string.sex_boy)) ? 1 : label.equals(context.getString(R.string.sex_girl)) ? 2 : 3;
                    viewModel.sex.setValue(label);
                } else {
                    followStatusCode = followStatusData.get(position).getNum();
                    viewModel.followStatus.setValue(followStatus.get(position));
                }
            }
        };
        singlePickerView.showSinglePickerView();
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initClick() {
        viewModel.onDelayClick(binding.rlSex, o -> {
            CommonUtil.closeKeyboard(this);
            initSinglePickerView(1, sexData, context.getString(R.string.sex));
        });
        viewModel.onDelayClick(binding.rlContactsFrom, o -> {
            Intent intent = new Intent(this, ProductActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.flagKey, 2);
            bundle.putSerializable(Constant.listKey, sourceData);
            intent.putExtras(bundle);
            requestAddSource.launch(intent);
        });
        viewModel.onDelayClick(binding.rlFollowStatus, o -> initSinglePickerView(2, followStatus, getString(R.string.follow_status)));
        viewModel.onDelayClick(binding.tvAddTag, o -> addTagDialog.showDialog());
        viewModel.onDelayClick(binding.ivUploadImg, o -> PictureSelector.create(context).openGallery(SelectMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .setImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                .setSelectorUIStyle(new PictureSelectorStyle())
                .setCameraImageFormat(PictureMimeType.PNG) // 拍照保存图片格式后缀,默认jpeg,Android Q使用PictureMimeType.PNG_Q
                .setSelectionMode(SelectModeConfig.SINGLE) // 单选
                .setCompressEngine((CompressFileEngine) (context, source, call) -> Luban.with(context).load(source).ignoreBy(100)
                        .setCompressListener(new OnNewCompressListener() {
                            @Override
                            public void onStart() {
                            }

                            @Override
                            public void onSuccess(String source, File compressFile) {
                                if (call != null) {
                                    call.onCallback(source, compressFile.getAbsolutePath());
                                }
                            }

                            @Override
                            public void onError(String source, Throwable e) {
                                if (call != null) {
                                    call.onCallback(source, null);
                                }
                            }
                        }).launch())
                .forResult(launcherResult));
        viewModel.onDelayClick(binding.btnConfirm, o -> {
            UMengUtil.setCountEventId(Constant.SAVE_CONTACTS);
            if (historyTagsData2.size() == 0) {
                Map<String, Object> map = new ArrayMap<>();
                map.put("compNameList", companyData);
                map.put("contactSourceType", contactSourceType);
                map.put("contactSource", contactSource);
                map.put("followStatus", followStatusCode);
                map.put("contactWeight", viewModel.weight.getValue());
                map.put("labelList", mTags);
                map.put("remark", viewModel.remark.getValue());
                map.put("sex", sex);
                map.put("username", viewModel.userName.getValue().trim());
                map.put("tels", numData);
                map.put("attachmentList", imgList);
                if (TextUtils.isEmpty(contactId)) {
                    viewModel.saveContacts(map);
                } else {
                    viewModel.editContacts(map, contactId);
                }
            } else {
                viewModel.deleteAllTag(historyTagsData2);
            }
        });

        viewModel.imgData.observe(this, url -> {
            Glide.with(context).load(url).into(binding.ivUploadImg);
            imgList.clear();
            imgList.add(new FileModel(file.getName(), url, 1));
        });

        viewModel.addContactsSuccessData.observe(this, o -> {
            if (flag == 3) {
                EventBus.getDefault().post(new EventBusModel(Constant.refreshCompanyList));
                EventBus.getDefault().post(new EventBusModel(Constant.refreshCompanyContactsWay));
            }
            ToastHelper.show(TextUtils.isEmpty(contactId) ? getString(R.string.add_contacts_success) : getString(R.string.edit_contacts_success));
            AddContactsActivity.this.finish();
        });

        // -------------------标签相关-----------------------
        viewModel.historyTagsData.observe(this, contactsTagModels -> {
            if (null != contactsTagModels && contactsTagModels.size() > 0) {
                historyTags.clear();
                historyTagsData = contactsTagModels;
                for (ContactsTagModel contactsTagModel : historyTagsData) {
                    historyTags.add(contactsTagModel.getLabelContent());
                }
                binding.tagLayoutHistory.setTags(historyTags);
            }
            if (!TextUtils.isEmpty(contactId)) {
                viewModel.getContactsDetails(contactId, contactType);
            }
        });

        // -------------------编辑联系人相关-----------------------
        viewModel.detailsModel.observe(this, model -> {
            numData = model.getTels();
            contactsPhoneAdapter.onRefresh(numData);

            companyData = model.getCompNameList();
            if (companyData == null) {
                companyData = new ArrayList<>();
            }
            if (companyData.size() == 0) {
                companyData.add(new CompanyModel());
            }
            companyAdapter.onRefresh(companyData);
            contactSourceType = model.getContactSourceType();
            contactSource = model.getContactSource();
            sex = model.getSex();
            viewModel.sex.setValue(sex == 1 ? getString(R.string.sex_boy) : sex == 2 ? getString(R.string.sex_girl) : getString(R.string.unknown));
            viewModel.userName.setValue(model.getUsername());
            viewModel.contactFrom.setValue(contactSource);
            viewModel.weight.setValue(String.valueOf(model.getContactWeight()));
            viewModel.remark.setValue(model.getRemark());
            followStatusCode = model.getFollowStatus();
            viewModel.followStatus.setValue(model.getFollowStatusName());
            if (null != model.getLabelList() && model.getLabelList().size() > 0) {
                mTags = model.getLabelList();
                binding.tagLayout.setTags(mTags);
                for (int i = 0; i < mTags.size(); i++) {
                    String tagTitle = mTags.get(i);
                    if (historyTags.contains(tagTitle)) {
                        int index = historyTags.indexOf(tagTitle);
                        binding.tagLayoutHistory.setSelect(index);
                    }
                    binding.tagLayout.setSelect(i);
                }
            } else {
                // 部门和全部联系人里只能看见自己的标签，并且不可编辑，我的里可以
                if (flag != 0 && contactType != 1) {
                    binding.llTagContainer.setVisibility(View.GONE);
                }
            }
            changeBtnStatus();
        });

        viewModel.userName.observe(this, o -> changeBtnStatus());
        viewModel.weight.observe(this, o -> changeBtnStatus());

        binding.etWeight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().startsWith("0")) {
                    editable.clear();
                    viewModel.weight.setValue("");
                }
            }
        });
        binding.tagLayout.setOnTagListener(new TagContainerLayout.TagListener() {
            @Override
            public void onTagClick(int position) {
            }

            @Override
            public void removeTag(int position) {
                binding.tagLayout.removeTag(position);
                String tagTitle = mTags.get(position);
                if (historyTags.contains(tagTitle)) {
                    int index = historyTags.indexOf(tagTitle);
                    binding.tagLayoutHistory.unSelect(index);
                }

                mTags.removeIf(s -> s.equals(tagTitle));
            }
        });

        binding.tagLayoutHistory.setOnTagListener(new TagContainerLayout.TagListener() {
            @Override
            public void onTagClick(int position) {
                if (binding.tagLayoutHistory.isSelcet(position)) {
                    binding.tagLayoutHistory.unSelect(position);
                    String tagTitle = historyTags.get(position);
                    if (mTags.size() > 0) {
                        int index = mTags.indexOf(tagTitle);
                        binding.tagLayout.removeTag(index);
                    }
                    mTags.removeIf(s -> s.equals(tagTitle));
                } else {
                    binding.tagLayoutHistory.setSelect(position);
                    String tagTitle = historyTags.get(position);
                    mTags.add(tagTitle);
                    binding.tagLayout.addTag(tagTitle);
                    int index = mTags.indexOf(tagTitle);
                    binding.tagLayout.setSelect(index);
                }
            }

            @Override
            public void removeTag(int position) {
                mPosition = position;

                String tagTitle = historyTags.get(mPosition);
                if (mTags.size() > 0) {
                    int index = mTags.indexOf(historyTags.get(mPosition));
                    binding.tagLayout.removeTag(index);
                }

                mTags.removeIf(s -> s.equals(tagTitle));

                for (ContactsTagModel contactsTagModel : historyTagsData) {
                    if (contactsTagModel.getLabelContent().equals(tagTitle)) {
                        historyTagsData2.add(contactsTagModel);
                    }
                }

                binding.tagLayoutHistory.removeTag(mPosition);
                historyTags.removeIf(s -> s.equals(tagTitle));
            }
        });

        viewModel.deleteTagStr.observe(this, o -> {
            Map<String, Object> map = new ArrayMap<>();
            map.put("compNameList", companyData);
            map.put("contactSourceType", contactSourceType);
            map.put("contactSource", contactSource);
            map.put("followStatus", followStatusCode);
            map.put("contactWeight", viewModel.weight.getValue());
            map.put("labelList", mTags);
            map.put("remark", viewModel.remark.getValue());
            map.put("sex", sex);
            map.put("username", viewModel.userName.getValue().trim());
            map.put("tels", numData);
            map.put("attachmentList", imgList);
            if (TextUtils.isEmpty(contactId)) {
                viewModel.saveContacts(map);
            } else {
                viewModel.editContacts(map, contactId);
            }
        });

        binding.tvEditTag.setOnClickListener(view -> {
            isEditTag = !isEditTag;
            binding.tagLayoutHistory.setEnableCross(isEditTag);
            binding.tagLayoutHistory.setTagEnable(!isEditTag);
        });

        binding.etNote.setOnTextChangeListener(text -> binding.tvTextCount.setText(getString(R.string.text_count_6, text.toString().trim().length())));
    }

    @Override
    public void onCompanyChangeListener(List<CompanyModel> list) {
        this.companyData = list;
        changeBtnStatus();
    }

    @Override
    public void onPhoneChangeListener(List<ContactWayModel> list) {
        this.numData = list;
        changeBtnStatus();
    }

    private void initDialog() {
        addTagDialog = new EditDialog(AddContactsActivity.this) {
            @Override
            public void rightClick(String content) {
                if (historyTags.contains(content)) {
                    int index = historyTags.indexOf(content);
                    binding.tagLayoutHistory.setSelect(index);
                }
                if (!mTags.contains(content)) {
                    mTags.add(content);
                    binding.tagLayout.addTag(content);
                    int index = mTags.indexOf(content);
                    binding.tagLayout.setSelect(index);
                }
            }
        };
        addTagDialog.setContent(getString(R.string.add_contacts_tag), getString(R.string.input_tag_name));
    }

    private void changeBtnStatus() {
        boolean isALlContact = true;
        for (int i = 0; i < numData.size(); i++) {
            ContactWayModel contactWayModel = numData.get(i);
            if (TextUtils.isEmpty(contactWayModel.getInfo())) {
                isALlContact = false;
                break;
            } else {
                if (contactWayModel.getType() == 1) {
                    if (contactWayModel.getInfo().length() < 11 || !contactWayModel.getInfo().startsWith("1")) {
                        isALlContact = false;
                    }
                }
                if (contactWayModel.getType() == 4 && !CommonUtil.isEmail(contactWayModel.getInfo())) {
                    isALlContact = false;
                }
            }
        }

        boolean isALlCompany = true;
        for (CompanyModel companyModel : companyData) {
            if (companyModel.getCompanyStatus() == 0) {
                isALlCompany = false;
            }
            if (companyModel.getCompanyStatus() == 1 && (companyModel.getCompName() == null || companyModel.getCompName().trim().length() == 0)) {
                isALlCompany = false;
            }
        }

        if (isALlContact && isALlCompany && viewModel.userName.getValue() != null
                && viewModel.userName.getValue().trim().length() > 0
                && !TextUtils.isEmpty(viewModel.contactFrom.getValue())
                && !TextUtils.isEmpty(viewModel.weight.getValue())) {
            binding.btnConfirm.setEnabled(true);
            binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_sel);
        } else {
            binding.btnConfirm.setEnabled(false);
            binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_def);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding.tagLayoutHistory.removeAllTags();
    }

    /**
     * 创建一个ActivityResultLauncher
     */
    private ActivityResultLauncher<Intent> createActivityResultLauncher() {
        return registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            int resultCode = result.getResultCode();
            if (resultCode == RESULT_OK) {
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(result.getData());
                for (int i = 0; i < selectList.size(); i++) {
                    LocalMedia media = selectList.get(i);
                    file = new File(media.getCompressPath() == null ? media.getRealPath() : media.getCompressPath());
                    viewModel.uploadImage(file);
                }
            }
        });
    }
}